<script setup>
import { User, Lock, DocumentChecked, Message } from "@element-plus/icons-vue";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { sendVerificationCodeService,passwordLoginService,verificationLoginService,forgetPasswordService } from '@/api/user';
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();
const router = useRouter();

const isLogin = ref(true);
const ruleForm = ref();
const ruleForm2 = ref();
const ruleForm3 = ref();
const activeName = ref("password"); //激活选项卡
const formModel = ref({
  userName: "",
  email: "",
  verification: "",
  password: "",
});
const rules = {
  password: [{ required: true, message: "请输入密码" }],
  email: [
    { required: true, message: "请输入邮箱" },
    { type: "email", message: "邮箱格式不正确" },
  ],
  verification: [{ required: true, message: "请输入验证码" }],
};

const seconds = 30;
const currentSeconds = ref(seconds);
const timer = ref();
const emailFormItem = ref();



//调接口发送邮箱验证码
const sendEmailCode = async () => {
  //存在倒计时则返回
  if (timer.value) {
    return;
  }
  //校验邮箱
  await emailFormItem.value.validate();

  const res = await sendVerificationCodeService(formModel.value.email);
  ElMessage.success("验证码发送成功请查收邮箱");
  console.log(res);

  timer.value = setInterval(() => {
    currentSeconds.value--;
    if (currentSeconds.value === 0) {
      currentSeconds.value = seconds;
      clearInterval(timer.value);
      timer.value = null;
    }
  }, 1000);
};

//登录
const submitForm = async () => {
  let res
  //密码登录
  if (activeName.value == "password") {
    await ruleForm.value.validate();
    res=await passwordLoginService(formModel.value.email,formModel.value.password)

  } else {
    //验证码登录
    await ruleForm2.value.validate();
    res=await verificationLoginService(formModel.value.email,formModel.value.verification)
  }
  console.log(res)
  ElMessage.success('登录成功')
  //验证成功存入store,userId
  userStore.setToken(res.data.jwtToken);
  userStore.setUserId(res.data.userId)
  await userStore.getInformation()
  //登录成功后路由跳转到管理员主页或者用户主页
  if(res.data.permission=='管理员'){
    router.push("/admin");
  }else{
    router.push("/home");
  }
 
};

const forgotPassword=async()=>{
  await ruleForm3.value.validate()
  const res=await forgetPasswordService(formModel.value.email,formModel.value.verification,formModel.value.password)
  ElMessage.success('修改成功')
  isLogin.value=true
  console.log(res)
}
</script>
<template>
  <div>
    <el-container>
      <el-header>
        <div style="text-align: center; font-size: 25px; font-weight: bolder">
          <h3>言智空间</h3>
        </div>
      </el-header>

      <el-main>
        <el-card class="login-module" v-if="isLogin">
          <el-tabs
            :stretch="true"
            v-model="activeName"
            class="demo-tabs"
            @tab-click="handleClick"
            v-if="isLogin"
          >
            <el-tab-pane label="密码登录" name="password">
              <div>
                <el-form
                  style="width: 500px; margin-left: 85px; padding-top: 40px"
                  :model="formModel"
                  :rules="rules"
                  ref="ruleForm"
                  label-position="left"
                  label-width="auto"
                >
                  <el-form-item prop="email" label="邮箱">
                    <el-input
                      v-model="formModel.email"
                      placeholder="请输入邮箱"
                      size="large"
                      :prefix-icon="User"
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="password" label="密码">
                    <el-input
                      v-model="formModel.password"
                      placeholder="请输入密码"
                      size="large"
                      show-password
                      :prefix-icon="Lock"
                    ></el-input>
                  </el-form-item>
                  <el-form-item style="padding-left: 40%; padding-top: 20px">
                    <el-button type="primary" @click="submitForm()"
                      >登录</el-button
                    >
                    <el-button @click="ruleForm.resetFields()">重置</el-button>
                   
                    
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>

            <el-tab-pane label="验证码登录" name="email">
              <div>
                <el-form
                  style="width: 500px; margin-left: 85px; padding-top: 40px"
                  :model="formModel"
                  :rules="rules"
                  ref="ruleForm2"
                  label-position="left"
                  label-width="auto"
                >
                  <el-form-item ref="emailFormItem" prop="email" label="邮箱">
                    <el-input
                      v-model="formModel.email"
                      size="large"
                      placeholder="请输入邮箱"
                      :prefix-icon="Message"
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="verification" label="邮箱验证码">
                    <el-input
                      size="large"
                      style="width: 60%"
                      v-model="formModel.verification"
                      placeholder="请输邮箱验证码"
                      :prefix-icon="DocumentChecked"
                    ></el-input>

                    <el-button
                      :disabled="currentSeconds != seconds"
                      @click="sendEmailCode()"
                      style="margin-left: 30px"
                      plain
                      >{{
                        currentSeconds === seconds
                          ? "获取邮箱验证码"
                          : currentSeconds + "秒后重新获取"
                      }}</el-button
                    >
                  </el-form-item>
                  <el-form-item style="padding-left: 40%; padding-top: 21px">
                    <el-button type="primary" @click="submitForm()"
                      >登录</el-button
                    >
                    <el-button @click="ruleForm2.resetFields()">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>

          
          

          <el-form-item style="padding-left: 90%; margin-bottom: 0px">
            <el-link
              style=""
              type="info"
              :underline="false"
              @click="router.push('/register')"
            >
              注册 →
            </el-link>
            <el-link
              v-if="activeName == 'password'"
              style=""
              type="info"
              :underline="false"
              @click="{ruleForm?.resetFields();isLogin=false;}"
            >
              忘记密码 ?
            </el-link>
          </el-form-item>
        </el-card>

        <el-card class="login-module" v-else>
            <template v-slot:header>
              <span
                style="
                  text-align: center;
                  font-size: 20px;
                  font-family: 'Microsoft YaHei';
                "
              >
                忘记密码
              </span>
              
            </template>
            <div>
              <el-form
                style="width: 500px; margin-left: 85px"
                :model="formModel"
                :rules="rules"
                ref="ruleForm3"
                label-position="left"
                label-width="auto"
              >
                <el-form-item ref="emailFormItem" prop="email" label="邮箱">
                  <el-input
                    v-model="formModel.email"
                    placeholder="请输入邮箱"
                    :prefix-icon="Message"
                  ></el-input>
                </el-form-item>

                <el-form-item prop="verification" label="邮箱验证码">
                  <el-input
                   
                    v-model="formModel.verification"
                    placeholder="请输邮箱验证码"
                    :prefix-icon="DocumentChecked"
                  >
                  <template #append>
                    
                    <el-button
                    :disabled="currentSeconds != seconds"
                    @click="sendEmailCode()"
                  
                    plain
                    >{{
                      currentSeconds === seconds
                        ? "获取邮箱验证码"
                        : currentSeconds + "秒后重新获取"
                    }}</el-button>

                  </template>
                </el-input>
                </el-form-item>

                <el-form-item prop="password" label="新密码">
                  <el-input
                    v-model="formModel.password"
                    placeholder="请输入新密码"
                    show-password
                    :prefix-icon="Lock"
                  ></el-input>
                </el-form-item>
                <el-form-item style="padding-left: 40%">
                  <el-button type="success" @click="forgotPassword">完成</el-button>
                  <el-button type="" @click="{ruleForm3.resetFields();isLogin=true}">返回</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
      </el-main>
    </el-container>
  </div>
</template>
<style>
.login-module {
  /*width: 380px;*/
  /*height: 325px;*/
  margin: auto;
  margin-top: 60px;
  /*border: none;*/
  /* position: absolute; */
  right: 500px;
  text-align: center;
  width: 50%;
}
</style>
